// components/sound-record-two/index.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import { initLocationPersmiss } from '../../utils/util';
const $api = require('../../request/api').API;
const app = getApp();
const ARR = [];
const recorderManager = wx.getRecorderManager();
const innerAudioContext = wx.createInnerAudioContext();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    beeperId: {
      type: String || Number
    },
    btnId: {
      type: String || Number
    },
    btnType: {
      type: String || Number
    },
    queryType: {
      type: String || Number
    },
    btnServerClassifyIds: {
      type: String || Number
    },
    delay: {
      type: Number,
      value: 0
    },
    title: {
      type: String,
      value: '保存录音'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    show: false,
    showRecord: false,
    showPlay: false,
    progress: 0,
    gradientColor: {
      '0%': '#ffd01e',
      '100%': '#ee0a24'
    },
    tempRecordFile: '',
    // stopRecord用来限制录音开始操作，如果快速点击录音然后松开会导致结束录音还没有执行
    // stopRecord:false,
    isPlay: false,
    // authorize:false,//是否开启录音授权
    // 录音配置选项
    options: {
      duration: 20000, //指定录音的时长，单位 ms
      sampleRate: 16000, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 96000, //编码码率
      format: 'mp3', //音频格式，有效值 aac/mp3
      frameSize: 50 //指定帧大小，单位 KB
    },
    showPhonePopup: false,
    phone: '',
    code: '',
    second: '',
    recordDuration: 0
  },

  /**
   * 组件的方法列表
   */
  lifetimes: {
    attached() {
      // this.recorderManager = wx.getRecorderManager()
      // this.innerAudioContext = wx.createInnerAudioContext()
      // this.watch()
    },
    detached() {
      // this.recorderManager = wx.getRecorderManager()
      // this.innerAudioContext = wx.createInnerAudioContext()
    }
  },
  pageLifetimes: {
    show() {
      // this.recorderManager = wx.getRecorderManager()
      // this.innerAudioContext = wx.createInnerAudioContext()
      // this.watch()
    }
  },
  methods: {
    // 隐藏录音组件
    hidePopup() {
      this.setData({
        show: false,
        isPlay: false,
        showPlay: false,
        tempRecordFile: ''
      });
      // recorderManager.onStop()
    },
    // 阻止冒泡
    stopBubble() {},
    // 监听录音和播放
    watch() {
      recorderManager.onStart(res => {
        if (this.endRecord) {
          this.recorderManager.stop();
          this.endRecord = false;
          return;
        }
        this.timer = setInterval(() => {
          this.setData({
            progress: this.data.progress + 0.125
          });
        }, 20);
        wx.vibrateLong();
        this.setData({
          showRecord: true,
          show: true,
          progress: 0,
          tempRecordFile: ''
          // showPlay:false
        });
        // 录音进度条
      });
      // 监听录音停止
      recorderManager.onStop(res => {
        // console.log(res)
        clearTimeout(this.timer);
        this.setData({
          showRecord: false
        });
        if (this.data.progress < 5) {
          this.setData({
            showPlay: false,
            show: false
          });
          Toast.fail('录音时间太短');
          return;
        } else {
          this.setData({
            showPlay: true
          });
        }
        console.log('停止', res.tempFilePath);
        this.setData({
          tempRecordFile: res.tempFilePath,
          recordDuration: res.duration
          // show:true
        });
      });
      // 监听开始播放
      innerAudioContext.onPlay(() => {
        this.setData({
          isPlay: true
        });
      });
      // 监听听停止播放
      innerAudioContext.onStop(() => {
        this.setData({
          isPlay: false
        });
      });
      // 监听播放结束
      innerAudioContext.onEnded(() => {
        this.setData({
          isPlay: false
        });
      });
    },
    // 长按录音
    start() {
      this.watch();
      // 开始录音
      if (this.pause) {
        return;
      }
      setTimeout(() => {
        this.pause = false;
      }, 400);

      if (app.globalData.recordSound) {
        this.pause = true;
        this.endRecord = false;
        recorderManager.start(this.data.options);
      } else if (app.globalData.hasOwnProperty('recordSound')) {
        wx.showModal({
          title: '提示',
          content: '您未授权录音，功能将无法使用',
          showCancel: true,
          confirmText: '授权',
          confirmColor: '#52a2d8',
          success: function (res) {
            if (res.confirm) {
              //确认则打开设置页面（重点）
              wx.openSetting({
                success: res => {
                  if (!res.authSetting['scope.record']) {
                    wx.showToast({
                      type: 'fail',
                      title: '授权失败'
                    });
                  } else {
                    wx.showToast({
                      type: 'success',
                      title: '授权成功'
                    });
                    app.globalData.recordSound = true;
                    //第二次才成功授权
                  }
                }
              });
            }
          }
        });
      } else {
        wx.authorize({
          scope: 'scope.record',
          success: () => {
            app.globalData.recordSound = true;
          }
        });
      }
    },
    // 松开结束录音
    end() {
      this.endRecord = true;
      if (app.globalData.recordSound) {
        recorderManager.stop();
      }
    },
    //开始录音
    startRecord: function () {
      var that = this;
      //开始录音
      wx.getSetting({
        success: res => {
          // 判断是不是第一次授权
          let first = res.authSetting['scope.record'] === undefined;
          wx.authorize({
            scope: 'scope.record',
            success(res) {
              that.data.authorize = true;
              if (first) return;
              if (that.data.stopRecord) return;
              recorderManager.start(that.data.options);
            },
            fail() {
              wx.showModal({
                title: '提示',
                content: '您未授权录音，功能将无法使用',
                showCancel: true,
                confirmText: '授权',
                confirmColor: '#52a2d8',
                success: function (res) {
                  if (res.confirm) {
                    //确认则打开设置页面（重点）
                    wx.openSetting({
                      success: res => {
                        console.log(res.authSetting);
                        if (!res.authSetting['scope.record']) {
                          //未设置录音授权
                          console.log('未设置录音授权');
                          wx.showModal({
                            title: '提示',
                            content: '您未授权录音，功能将无法使用',
                            showCancel: false,
                            success: res => {}
                          });
                        } else {
                          //第二次才成功授权
                          that.data.authorize = true;
                          if (first) return;
                          if (that.data.stopRecord) return;
                          ecorderManager.start(options);
                        }
                      },
                      fail: function () {
                        console.log('授权设置录音失败');
                      }
                    });
                  } else if (res.cancel) {
                    console.log('cancel');
                  }
                },
                fail: function () {
                  console.log('openfail');
                }
              });
            }
          });
        }
      });
    },
    // 播放录音
    playRecord() {
      innerAudioContext.autoplay = true;
      innerAudioContext.src = this.data.tempRecordFile;
    },
    // 停止播放录音
    stopPlay() {
      innerAudioContext.stop();
    },
    delContent(e) {
      const prop = e.currentTarget.dataset.prop;
      this.setData({
        [prop]: ''
      });
    },
    // 获取验证码
    getCode() {
      const { phone } = this.data;
      const reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
      if (!reg.test(phone)) {
        Toast.fail('手机号码格式不正确');
        return;
      }
      const params = {
        mobile: phone,
        smsType: 103,
        useType: 1
      };
      this.setData({
        second: 60
      });
      this.timer = setInterval(() => {
        this.setData({
          second: this.data.second - 1
        });
        if (this.data.second == 0) {
          clearInterval(this.timer);
        }
      }, 1000);
      $api.getPhoneCode(params).then(res => {
        if (res.data.status == 0) {
          wx.showToast({
            title: '发送验证码成功',
            status: 'success'
          });
        }
      });
    },
    inputChange(e) {
      const prop = e.currentTarget.dataset.prop;
      this.setData({
        [prop]: e.detail.value
      });
    },
    // 取消
    cancelBind() {
      this.setData({
        showPhonePopup: false
      });
    },
    // 确定
    async confirmBind() {
      const reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
      const { phone, code } = this.data;
      if (!reg.test(phone)) {
        Toast.fail('手机号格式错误');
        return;
      }
      if (!code) {
        Toast.fail('请填写验证码');
        return;
      }

      const params = {
        phone: phone,
        code
      };
      Toast.loading({
        message: '订单提交中',
        forbidClick: true,
        duration: 0
      });
      await $api.setUserPhone(params);
      this.cancelBind();
      this.userApi(this.params);
    },
    // 提交订单
    submitOrder() {
      Toast.loading({
        message: '订单提交中',
        forbidClick: true,
        duration: 0
      });
      wx.getFileSystemManager().readFile({
        filePath: this.data.tempRecordFile,
        encoding: 'base64',
        success: res => {
          let params = {
            beeperId: this.data.beeperId,
            btnType: this.data.btnType,
            btnId: this.data.btnId,
            btnServerClassifyIds: this.data.btnServerClassifyIds,
            queryType: this.data.queryType,
            audio: res.data
          };
          if (this.data.btnId) {
            params.btnId = this.data.btnId;
          }
          if (params.beeperId == -1) {
            params.beeperId = '';
            params.queryType = 0;
            initLocationPersmiss().then(res => {
              (params.latitude = res.location.lat),
                (params.longitude = res.location.lng),
                (params.provinceName = res.address_component.province),
                (params.cityName = res.address_component.city),
                (params.areaName = res.address_component.district),
                (params.streetName = res.address_component.street);
              params.address = res.formatted_addresses.recommend;
              this.userApi(params);
            });
          } else {
            this.userApi(params);
          }
        },
        fail: err => {
          Toast.clear();
        }
      });
    },
    // 调用订单接口
    async userApi(params) {
      const res = await $api.getUserPhone();
      if (!res.data.data) {
        Toast.clear();
        this.setData({
          showPhonePopup: true
        });
        this.params = params;
        return;
      }
      const res2 = await $api.voiceAddOrder(params);
      Toast.clear();
      let data = res2.data.data;
      if (data == 3) {
        app.globalData.soundOrder = true;
        wx.navigateTo({
          url: '/subcontract/person/pages/beeperAddress/index?id=' + this.data.beeperId
        });

        return;
      }
      Toast.success({
        message: '下单成功',
        forbidClick: true
      });
      setTimeout(() => {
        this.hidePopup();
        app.globalData.beeperOrderId = this.data.beeperId;
        wx.switchTab({
          url: '/pages/order/index'
        });
      }, 2000);
    },
    // 保存
    saveRecord() {
      let tempRecordFile = this.data.tempRecordFile;
      wx.getFileSystemManager().readFile({
        filePath: tempRecordFile,
        encoding: 'base64',
        success: res => {
          const { title, recordDuration } = this.data;
          if (title == '保存录音') {
            wx.showToast({
              title: '保存成功'
            });
          }
          this.triggerEvent('saveRecord', { duration: recordDuration, file: res.data, tempFilePath: tempRecordFile });
          this.hidePopup();
        },
        fail: err => {
          wx.showToast({
            title: '失败'
          });
        }
      });
    }
  }
});
